package cn.zhangxin.pethome.config;

import cn.zhangxin.pethome.annotation.PreAuthorize;
import cn.zhangxin.pethome.constants.BaseConstants;
import cn.zhangxin.pethome.jwt.LoginContextUtils;
import cn.zhangxin.pethome.jwt.Payload;
import cn.zhangxin.pethome.jwt.PayloadData;
import cn.zhangxin.pethome.system.employee.domain.Employee;
import cn.zhangxin.pethome.system.employee.service.IEmployeeService;
import cn.zhangxin.pethome.system.logininfo.domain.Logininfo;
import cn.zhangxin.pethome.system.logininfo.domain.LogininfoBO;
import cn.zhangxin.pethome.system.logininfo.service.ILogininfoService;
import cn.zhangxin.pethome.system.user.domain.User;
import cn.zhangxin.pethome.utils.JwtUtils;
import cn.zhangxin.pethome.utils.RsaUtils;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import sun.rmi.runtime.Log;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.security.PublicKey;
import java.util.Date;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;

//springboot集成springmvc的拦截器
@Component
public class LoginInterceptor implements HandlerInterceptor {
    private final String NO_LOGIN= "{\"success\":false,\"msg\":\"noLogin\"}";
    private final String NO_PERMISSION = "{\"success\":false,\"msg\":\"noPermission\"}";
    @Autowired
    private RedisTemplate redisTemplate;
    @Value("${jwt.rsa.pub}")
    private String pub;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取前端传进来的token
        String toKen = request.getHeader("token");
        if(toKen == null){
            setErrorMsg(response,NO_LOGIN);
            return false;
        }

        //根据传进来的token进行解析
        PublicKey publicKey = RsaUtils.getPublicKey(JwtUtils.class.getClassLoader().getResource(pub).getFile());
        Payload<PayloadData> o = null;
        try {
            o = JwtUtils.getInfoFromToken(toKen, publicKey, PayloadData.class);
        }catch (Exception e){
            setErrorMsg(response,NO_LOGIN);
            return false;
        }
        //刷新
        Date expiration = o.getExpiration();
        //刷新时间
        DateTime refreshTime = new DateTime(expiration).minusMinutes(5);//过期前多少分钟
        //当前时间在刷新时间之后就要刷新一把
        if(refreshTime.isBefore(DateTime.now())){
            //重新登录刷新token          response.getWriter().write("{\"success\":false,\"message\":\"noLogin\"}");
            setErrorMsg(response,NO_LOGIN);
            return false;
        }



        //获取你请求的那个接口的自定义注解
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        PreAuthorize preAuthorize = handlerMethod.getMethodAnnotation(PreAuthorize.class);
        //3.判断preAuthorize 是否有值
        if(preAuthorize == null){
            return true;
        }

        //3.1 有，校验是否有权限访问
        String sn = preAuthorize.sn();//需要校验当前登录人，是否有权限访问该资源
        if(!o.getUserInfo().getPermissions().contains(sn)){
            setErrorMsg(response,NO_PERMISSION);
            return false;
        }
        return true;

    }

    private boolean redisToken(HttpServletRequest request, HttpServletResponse response, HandlerMethod handler) throws IOException {
        //获得token
        String token = request.getHeader("ToKen");
        if (token==null){
            setErrorMsg(response,NO_LOGIN);
            return false;
        }
        //拿到用户信息
        Object logininfo = redisTemplate.opsForValue().get(token);
        if (logininfo==null){
            setErrorMsg(response,NO_LOGIN);
            return false;
        }
        redisTemplate.opsForValue().set(token,logininfo,30, TimeUnit.MINUTES);

        List<String> permissionSn = (List<String>)redisTemplate.opsForValue().get(token + "permission");

        //2.如果是后端员工employee来操作的时候，才需要校验资源的访问权限
        //2.1 哪些请求需要校验权限 （答：打了自定义注解PreAuthorize权限的方法）
        HandlerMethod handlerMethod = handler;
        PreAuthorize preAuthorize = handlerMethod.getMethodAnnotation(PreAuthorize.class);
        //3.判断preAuthorize 是否有值
        if(preAuthorize == null){
            //3.2 没有，放行  公共资源不需要校验权限
            return true;
        }
        //3.1 有，校验是否有权限访问
        String sn = preAuthorize.sn();//需要校验当前登录人，是否有权限访问该资源

        if(!permissionSn.contains(sn)){
            setErrorMsg(response,NO_PERMISSION);
            return false;
        }
        return true;//false拦截
    }

    private void setErrorMsg(HttpServletResponse response,String msg) throws IOException {
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/json;charset=UTF-8");
        PrintWriter writer = response.getWriter();
        // 在外面写好在拷贝进去
        writer.write(msg);
        writer.close();
    }
}
